<!-- 我的评价页面 -->
<template>
  <div class="Comments">
    <h1 class="page-title">我的评价</h1>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 待评价标签页 -->
      <el-tab-pane label="待评价" name="pending">
        <!-- 待评价商品列表 -->
        <div v-if="pendingComments.length > 0" class="comment-list">
          <el-card
            v-for="item in pendingComments"
            :key="item.id"
            class="comment-item"
          >
            <div class="comment-product">
              <!-- 商品图片 -->
              <div class="product-img">
                <router-link
                  :to="{
                    path: '/goods/details',
                    query: { productID: item.product_id },
                  }"
                >
                  <img
                    :src="$target + item.product_picture"
                    :alt="item.product_name"
                  />
                </router-link>
              </div>

              <!-- 商品信息 -->
              <div class="product-info">
                <router-link
                  :to="{
                    path: '/goods/details',
                    query: { productID: item.product_id },
                  }"
                >
                  <div class="product-name">{{ item.product_name }}</div>
                </router-link>
                <div class="product-time">
                  购买时间：{{ item.order_time | dateFormat }}
                </div>
                <div class="order-id">订单号：{{ item.order_id }}</div>
              </div>

              <!-- 操作按钮 -->
              <div class="comment-actions">
                <el-button
                  type="primary"
                  size="small"
                  @click="showReviewDialog(item)"
                  >评价</el-button
                >
              </div>
            </div>
          </el-card>
        </div>

        <!-- 无待评价商品时显示 -->
        <div v-else class="empty-state">
          <i class="el-icon-shopping-cart-empty"></i>
          <p>暂无待评价商品</p>
        </div>
      </el-tab-pane>

      <!-- 已评价标签页 -->
      <el-tab-pane label="已评价" name="completed">
        <!-- 已评价商品列表 -->
        <div v-if="completedComments.length > 0" class="comment-list">
          <el-card
            v-for="item in completedComments"
            :key="item.id"
            class="comment-item"
          >
            <div class="comment-product">
              <!-- 商品图片 -->
              <div class="product-img">
                <router-link
                  :to="{
                    path: '/goods/details',
                    query: { productID: item.product_id },
                  }"
                >
                  <img
                    :src="$target + item.product_picture"
                    :alt="item.product_name"
                  />
                </router-link>
              </div>

              <!-- 商品信息 -->
              <div class="product-info">
                <router-link
                  :to="{
                    path: '/goods/details',
                    query: { productID: item.product_id },
                  }"
                >
                  <div class="product-name">{{ item.product_name }}</div>
                </router-link>
                <div class="product-time">
                  评价时间：{{ item.create_time | dateFormat }}
                </div>
                <div class="order-id" v-if="item.order_id">
                  订单号：{{ item.order_id }}
                </div>

                <!-- 评分显示 -->
                <div class="comment-score">
                  <span>评分：</span>
                  <el-rate
                    v-model="item.score"
                    disabled
                    text-color="#ff9900"
                  ></el-rate>
                </div>

                <!-- 评价内容 -->
                <div class="comment-content">
                  <p>{{ item.content }}</p>
                </div>

                <!-- 评价图片，如果有的话 -->
                <div
                  v-if="item.pictures && item.pictures.length > 0"
                  class="comment-pictures"
                >
                  <el-image
                    v-for="(pic, index) in item.pictures"
                    :key="index"
                    :src="pic"
                    :preview-src-list="item.pictures"
                    class="comment-picture"
                  ></el-image>
                  <!-- Element UI 的 el-image 组件提供的功能，
                      使用:preview-src-list 属性时，会自动启用图片预览功能，包括：
                          1.点击图片可以放大查看
                          2.在预览模式下，图片右上角会显示操作按钮：
                            旋转按钮（可以左右旋转）
                            放大/缩小按钮
                            关闭按钮 -->
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="comment-actions">
                <el-button
                  type="danger"
                  size="small"
                  @click="deleteReview(item.id)"
                  >删除评价</el-button
                >
              </div>
            </div>
          </el-card>
        </div>

        <!-- 无已评价商品时显示 -->
        <div v-else class="empty-state">
          <i class="el-icon-star-off"></i>
          <p>暂无已评价商品</p>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 评价对话框 -->
    <el-dialog title="发表商品评价" :visible.sync="dialogVisible" width="50%">
      <el-form :model="commentForm" label-width="80px">
        <!-- 商品信息展示 -->
        <div class="dialog-product-info" v-if="currentProduct">
          <img
            :src="$target + currentProduct.product_picture"
            :alt="currentProduct.product_name"
            class="dialog-product-img"
          />
          <div class="dialog-product-name">
            {{ currentProduct.product_name }}
          </div>
        </div>

        <!-- 评分 -->
        <el-form-item label="评分">
          <el-rate v-model="commentForm.score" :colors="colors"></el-rate>
        </el-form-item>

        <!-- 评价内容 -->
        <el-form-item label="评价内容">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请写下您对商品的评价..."
            v-model="commentForm.content"
          ></el-input>
        </el-form-item>

        <!-- 图片上传 -->
        <el-form-item label="上传图片">
          <el-upload
            action=""
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :auto-upload="false"
            :file-list="uploadPictures"
            :limit="5"
            multiple
            :on-change="handleChange"
          >
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过2MB
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogImageVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitReview">提交评价</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "MyComments",
  data() {
    return {
      activeTab: "pending", // 当前选中的标签页
      pendingComments: [], // 待评价商品列表
      completedComments: [], // 已评价商品列表
      dialogVisible: false, // 评价对话框可见性
      dialogImageVisible: false, // 预览图片对话框可见性
      dialogImageUrl: "", // 预览图片URL
      currentProduct: null, // 当前要评价的商品
      commentForm: {
        // 用于提交新评价的表单数据
        user_id: "", // 用户ID
        product_id: "", // 商品ID
        order_id: "", // 订单ID
        content: "", // 评价内容
        score: 5, // 默认评分
        pictures: [], // 评价图片
      },
      uploadPictures: [], // 上传的图片文件
      colors: ["#99A9BF", "#F7BA2A", "#FF9900"], // 评分颜色
    };
  },
  created() {
    // 获取用户信息并初始化
    this.initUserInfo();
    // 获取评价列表
    this.getReviewList();
  },
  methods: {
    // 初始化用户信息
    initUserInfo() {
      const user = this.$store.getters.getUser;
      if (user) {
        this.commentForm.user_id = user.user_id;
      }
    },
    // 获取评价列表
    getReviewList() {
      // 获取当前用户ID
      const user = this.$store.getters.getUser;
      if (!user) return;

      // 获取待评价商品列表（从订单中获取已完成但未评价的商品）
      this.$axios
        .post("/api/order/pendingComment", {
          user_id: user.user_id,
        })
        .then((res) => {
          if (res.data.code === "001") {
            // 获取数据
            this.pendingComments = res.data.data || [];

            // 处理每个商品项，设置默认值
            for (let i = 0; i < this.pendingComments.length; i++) {
              const item = this.pendingComments[i];
              // 设置默认值
              if (!item.product_name) item.product_name = "未知商品"; // 商品名
              if (!item.product_picture) item.product_picture = ""; // 商品封面
              if (!item.order_time) item.order_time = new Date().toISOString();
            }
          } else {
            this.$message.error(res.data.msg || "获取待评价商品失败");
          }
        })
        .catch((err) => {
          console.error("获取待评价商品失败:", err);
          this.$message.error("获取待评价商品失败，请稍后重试");
        });

      // 获取已评价商品列表
      this.$axios
        .post("/api/comment/list", {
          user_id: user.user_id,
        })
        .then((res) => {
          if (res.data.code === "001") {
            // 获取数据
            this.completedComments = res.data.data || [];

            // 处理每个评价项，设置默认值
            for (let i = 0; i < this.completedComments.length; i++) {
              const item = this.completedComments[i];
              // 设置默认值
              if (!item.product_name) item.product_name = "未知商品";
              if (!item.score) item.score = 5;
              if (!item.content) item.content = "";
              if (!item.pictures) item.pictures = [];
              if (!item.create_time)
                item.create_time = new Date().toISOString();
              // 确保订单号字段存在
              if (!item.order_id) item.order_id = "未知订单";
            }
          } else {
            this.$message.error(res.data.msg || "获取已评价商品失败");
          }
        })
        .catch((err) => {
          console.error("获取已评价商品失败:", err);
          this.$message.error("获取已评价商品失败，请稍后重试");
        });
    },
    // 切换标签页
    handleTabClick() {
      // 每次切换标签页都刷新数据
      this.getReviewList();
    },
    // 显示评价对话框
    showReviewDialog(product) {
      this.currentProduct = product;
      this.commentForm.product_id = product.product_id;
      this.commentForm.order_id = product.order_id; // 设置订单ID
      this.commentForm.content = "";
      this.commentForm.score = 5;
      // this.commentForm.pictures = [];
      this.uploadPictures = [];
      this.dialogVisible = true;
    },
    // 处理图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogImageVisible = true;
    },
    // 处理文件状态改变
    handleChange(file, fileList) {
      console.log("文件状态改变:", file, fileList);
      this.uploadPictures = fileList;
    },
    // 处理图片移除
    handleRemove(file, fileList) {
      console.log("移除文件:", file, fileList);
      this.uploadPictures = fileList;
    },
    // 图片上传前处理
    beforeUpload(file) {
      // 验证图片类型和大小
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("只能上传图片文件!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
        return false;
      }

      // 生成图片预览
      const reader = new FileReader();
      reader.readAsDataURL(file); // 将文件读取为DataURL
      reader.onload = () => {
        file.url = reader.result; // 将DataURL赋值给file对象的url属性
      };

      return false; // 阻止自动上传
    },
    // 提交评价
    async submitReview() {
      try {
        // 验证表单
        if (!this.commentForm.content) {
          this.$message.warning("请填写评价内容");
          return;
        }
        // 验证订单ID
        if (!this.commentForm.order_id) {
          this.$message.warning("订单信息有误，请刷新后重试");
          return;
        }
        console.log("提交评价时的uploadPictures:", this.uploadPictures);
        console.log("uploadPictures长度:", this.uploadPictures.length);
        // 1. 提交评价内容
        const res = await this.$axios.post(
          "/api/comment/save",
          this.commentForm
        );
        if (res.data.code !== "001") {
          this.$message.error(res.data.msg || "提交评价失败");
          return;
        }
        const commentId = res.data.data; // 获取新增评价的ID
        console.log("获取到的评价ID:", commentId);
        // 2. 上传图片（如果有）
        if (this.uploadPictures && this.uploadPictures.length > 0) {
          console.log("准备上传图片，commentId:", commentId);
          const formData = new FormData();
          // 遍历uploadPictures数组，添加每个文件
          for (let i = 0; i < this.uploadPictures.length; i++) {
            const file = this.uploadPictures[i];
            console.log("添加文件到FormData:", file);
            // 确保添加的是原始文件对象
            formData.append("files", file.raw || file);
          }
          formData.append("comment_id", commentId);
          console.log("FormData内容:", formData);
          try {
            const uploadRes = await this.$axios.post(
              "/api/comment/uploadPictures",
              formData,
              {
                headers: {
                  "Content-Type": "multipart/form-data",
                },
              }
            );
            console.log("图片上传结果:", uploadRes);
            if (uploadRes.data.code !== "001") {
              this.$message.warning("评价已提交，但图片上传失败");
            } else {
              this.$message.success("评价和图片上传成功");
            }
          } catch (uploadErr) {
            console.error("图片上传失败:", uploadErr);
            this.$message.warning("评价已提交，但图片上传失败");
          }
        } else {
          console.log("没有图片需要上传");
        }

        this.$message.success("评价提交成功");
        this.dialogVisible = false;
        this.getReviewList(); // 刷新列表
      } catch (err) {
        console.error("提交评价失败:", err);
        this.$message.error("提交评价失败，请稍后重试");
      }
    },
    // 删除评价
    deleteReview(id) {
      this.$confirm("确定要删除这条评价吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post("/api/comment/remove", {
              id: id,
            })
            .then((res) => {
              if (res.data.code === "001") {
                this.$message.success("评价删除成功");
                this.getReviewList(); // 刷新列表
              } else {
                this.$message.error(res.data.msg || "删除评价失败");
              }
            })
            .catch((err) => {
              console.error("删除评价失败:", err);
              this.$message.error("删除评价失败，请稍后重试");
            });
        })
        .catch(() => {
          // 取消删除，不做任何操作
        });
    },
  },
};
</script>

<style scoped>
.Comments {
  max-width: 1225px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

/* 评价列表样式 */
.comment-list {
  margin-top: 20px;
}

.comment-item {
  margin-bottom: 15px;
}

.comment-product {
  display: flex;
  align-items: flex-start;
}

.product-img {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border: 1px solid #f0f0f0;
  overflow: hidden;
  transition: all 0.3s ease;
}

.product-img:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.3s ease;
}

.product-img:hover img {
  transform: scale(1.1);
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.product-name:hover {
  color: #ff6700;
  text-decoration: underline;
}

.product-time,
.order-id {
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}

.comment-score {
  margin-bottom: 10px;
}

.comment-content {
  background: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 10px;
  color: #666;
  line-height: 1.5;
}

.comment-pictures {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.comment-picture {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.comment-actions {
  margin-left: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 评价对话框样式 */
.dialog-product-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #f0f0f0;
}

.dialog-product-img {
  width: 60px;
  height: 60px;
  margin-right: 15px;
  object-fit: cover;
  transition: all 0.3s ease;
  cursor: pointer;
}

.dialog-product-img:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-product-name {
  font-size: 16px;
  color: #333;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .comment-product {
    flex-direction: column;
  }

  .product-img {
    margin-bottom: 10px;
  }

  .comment-actions {
    margin-left: 0;
    margin-top: 15px;
  }
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p {
  font-size: 14px;
  margin: 0;
}
</style>
